/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dll.circular;
/**
*
* @author mweya
*/
import dll.circular.Node;
public class LinkedList<AnyType> {
private Node head = null;
//private Node tail = null;
public LinkedList() {
}
public LinkedList(AnyType data) {
head = new Node<>(data);
head.setNext(head);
head.setPrev(head);
}
public void addItem(AnyType data) {
if (head == null) {
head = new Node<>(data);
head.setNext(head);
head.setPrev(head);
} else {
Node currentNode = head;
while (currentNode.getNext() != head) {
currentNode = currentNode.getNext();
}
Node newInsert = new Node<>(data);
newInsert.setPrev(currentNode);
newInsert.setNext(head);
currentNode.setNext(newInsert);
head.setPrev(newInsert);
}
}
public String toStringRev() {
String out = "";
Node currentNode = head.getPrev();
while(currentNode != head) {
out = out+(String) currentNode.getData()+"\n";
currentNode = currentNode.getPrev();
}
// And print out the head too
out = out+(String) currentNode.getData()+"\n";
return out;
}
@Override
public String toString() {
//Print till we find the head again
String out = "";
Node currentNode = head;
do {
out = out+(String) currentNode.getData()+"\n";
currentNode = currentNode.getNext();
}
while(currentNode != head);
return out;
}
}